package com.returnsoft.softphone.service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;

import com.returnsoft.softphone.dto.SessionDto;
import com.returnsoft.softphone.eao.SessionEao;
import com.returnsoft.softphone.entity.Session;
import com.returnsoft.softphone.exception.ConversionExcepcion;
import com.returnsoft.softphone.exception.CCenterExcepcion;
import com.returnsoft.softphone.exception.EaoExcepcion;
import com.returnsoft.softphone.util.Conversion;

/**
 * Session Bean implementation class SessionTypeBean
 */
@Stateless
@LocalBean
public class SessionBean implements SessionInterface, Serializable {
	private static final long serialVersionUID = 1L;
	/*private final String SESSION_TYPE_SESSION = "session";
	private final String SESSION_TYPE_READY = "ready";
	private final String SESSION_TYPE_PAUSE = "pause";
	private final String SESSION_TYPE_BREAK = "break";
	private final String SESSION_TYPE_BREAK_WITH_CALL = "breakwithcall";
	private final String SESSION_TYPE_PAUSE_WITH_CALL = "pausewithcall";
	private final String SESSION_TYPE_LOGOUT_WITH_CALL = "logoutwithcall";
	private final String SESSION_TYPE_PAUSE_WITH_CLOSE = "pausewithclose";*/

	@EJB
	private SessionEao sessionEao;
	/*@EJB
	private CampaignEao campaignEao;
	@EJB
	private PeerEao peerEao;
	@EJB
	private AgentEao agentEao;
	@EJB
	private QueueEao queueEao;
	@EJB
	private ManagerBean managerBean;
	@EJB
	private SessionTypeEao sessionTypeEao;*/
	@EJB
	private Conversion conv;
	
	@Override
	public List<SessionDto> findSessionsForAgent(Date startedAt, Integer agentId) throws CCenterExcepcion{
	
		try {
			List<Session> sessions = sessionEao.findSessionsForAgent(startedAt, agentId);
			List<SessionDto> sessionsDto = new ArrayList<SessionDto>();
			for (Session session : sessions) {
				SessionDto sessionDto = conv.fromSession(session);
				sessionsDto.add(sessionDto);
			}
			return sessionsDto;
		} catch (EaoExcepcion e) {
			throw new CCenterExcepcion(e.getMessage());
		} catch (ConversionExcepcion e) {
			throw new CCenterExcepcion(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			throw new CCenterExcepcion(e.getMessage());
		}
	}
	
	@Override
	public List<SessionDto> findSessionsForSupervisor(List<Integer> sessionTypesId, List<Integer> campaignsId,
			List<Integer> supervisorsId, Date startedAt,
			String code, String name, String documentNumber, String username,
			String host, String peer, Boolean openSessions) throws CCenterExcepcion{
	
		try {
			List<SessionDto> sessions = sessionEao.findSessionsForSupervisor(sessionTypesId,campaignsId,
					supervisorsId,startedAt,
					 code,  name,  documentNumber,  username,
					 host,  peer,  openSessions);
			return sessions;
		} catch (EaoExcepcion e) {
			throw new CCenterExcepcion(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			throw new CCenterExcepcion(e.getMessage());
		}
	}

	/*@Override
	public String closeSessions(Integer agentId) throws CustomExcepcion {
		try {
			List<Campaign> campaigns = campaignEao.findByAgent(agentId);
			Agent agent = agentEao.findAgentById(agentId);
			Peer peer = peerEao.findPeer(agentId);
			SessionType sessionTypeSession = sessionTypeEao
					.findType(SESSION_TYPE_SESSION);

			for (Campaign campaign : campaigns) {

				// VERIFICA SESIONES ABIERTAS
				Session openSession = sessionEao.findOpenSession(
						campaign.getId(), agentId, sessionTypeSession.getId());

				if (openSession != null) {

					// SE CIERRA LA SESSION
					openSession.setEndedAt(new Date());
					sessionEao.createSession(openSession);

					// SE VERIFICAN ESTADOS ABIERTOS
					Session openState = sessionEao.findOpenStates(openSession
							.getId());
					if (openState != null) {
						// SE ACTUALIZA ESTADO ANTIGUO
						openState.setEndedAt(new Date());
						sessionEao.createSession(openState);

					}
				}

				// VERIFICA COLAS

				List<String> queues = queueEao.findQueues(campaign.getId());

				String respuesta = managerBean.removeManyQueues(queues, peer
						.getName(), peer.getServer().getIp(), peer.getServer()
						.getAmiUser(), peer.getServer().getAmiPassword(), peer
						.getServer().getAmiPort());
				if (!respuesta.equals("OK")) {
					throw new CustomExcepcion(
							"La respuesta del Manager es diferente de OK.");
				}

			}

			return "OK:"+peer.getName()+":"+agent.getCode();

		} catch (Exception e) {
			throw new CustomExcepcion(e.getMessage());
		}
	}

	@Override
	public List<SessionDto> changeState(Integer agentId, String host,
			String stateCode) throws CustomExcepcion {
		try {
			List<Campaign> campaigns = campaignEao.findByAgent(agentId);
			Agent agent = agentEao.findAgentById(agentId);
			Peer peer = peerEao.findPeer(agentId);
			SessionType sessionTypeSelected = sessionTypeEao
					.findType(stateCode);

			List<SessionDto> sessionsDto = new ArrayList<SessionDto>();

			for (Campaign campaign : campaigns) {

				// VERIFICA SESIONES ABIERTAS
				Session openSession = sessionEao.findOpenSession(
						campaign.getId(), agentId, sessionTypeSelected.getId());
				if (openSession != null) {
					// SE VERIFICAN ESTADOS ABIERTOS
					Session oldState = sessionEao.findOpenStates(openSession
							.getId());
					if (oldState != null) {
						// SE ACTUALIZA ESTADO ANTIGUO
						oldState.setEndedAt(new Date());
						sessionEao.createSession(oldState);
						// SE CREA NUEVO ESTADO
						Session newState = new Session();
						newState.setAgent(agent);
						newState.setCampaign(campaign);
						newState.setHost(host);
						//newState.setPeer(peer);
						newState.setSession(openSession);
						newState.setSessionType(sessionTypeSelected);
						newState.setStartedAt(new Date());
						newState = sessionEao.createSession(newState);
						sessionsDto.add(conv.fromSession(newState));
					} else {
						throw new CustomExcepcion("No existe estado activo.");
					}
				} else {
					throw new CustomExcepcion("No existe session activa.");
				}

				// VERIFICA COLAS

				if (sessionTypeSelected.getCode().equals(SESSION_TYPE_PAUSE)
						|| sessionTypeSelected.getCode().equals(
								SESSION_TYPE_BREAK)
						|| sessionTypeSelected.getCode().equals(
								SESSION_TYPE_BREAK_WITH_CALL)
						|| sessionTypeSelected.getCode().equals(
								SESSION_TYPE_PAUSE_WITH_CALL)
						|| sessionTypeSelected.getCode().equals(
								SESSION_TYPE_LOGOUT_WITH_CALL)
						|| sessionTypeSelected.getCode().equals(
								SESSION_TYPE_PAUSE_WITH_CLOSE)) {

					List<String> queues = queueEao.findQueues(campaign.getId());

					String respuesta = managerBean.pauseManyQueues(queues, peer
							.getName(), peer.getServer().getIp(), peer
							.getServer().getAmiUser(), peer.getServer()
							.getAmiPassword(), peer.getServer().getAmiPort());
					if (!respuesta.equals("OK")) {
						throw new CustomExcepcion(
								"La respuesta del Manager es diferente de OK.");
					}

				} else if (sessionTypeSelected.getCode().equals(
						SESSION_TYPE_READY)) {
					List<String> queues = queueEao.findQueues(campaign.getId());

					String respuesta = managerBean.unpauseManyQueues(queues,
							peer.getName(), peer.getServer().getIp(), peer
									.getServer().getAmiUser(), peer.getServer()
									.getAmiPassword(), peer.getServer()
									.getAmiPort());
					if (!respuesta.equals("OK")) {
						throw new CustomExcepcion(
								"La respuesta del Manager es diferente de OK.");
					}
				}

			}

			return sessionsDto;

		} catch (Exception e) {
			throw new CustomExcepcion(e.getMessage());
		}
	}

	@Override
	public List<SessionDto> checkSessions(Integer agentId, String host)
			throws CustomExcepcion {
		try {
			List<Campaign> campaigns = campaignEao.findByAgent(agentId);
			Agent agent = agentEao.findAgentById(agentId);
			Peer peer = peerEao.findPeer(agentId);
			SessionType sessionTypeSession = sessionTypeEao
					.findType(SESSION_TYPE_SESSION);
			SessionType sessionTypeReady = sessionTypeEao
					.findType(SESSION_TYPE_READY);
			SessionType sessionTypePause = sessionTypeEao
					.findType(SESSION_TYPE_PAUSE);

			List<SessionDto> sessionsDto = new ArrayList<SessionDto>();

			for (Campaign campaign : campaigns) {

				// VERIFICA SESIONES ABIERTAS
				Session openSession = sessionEao.findOpenSession(
						campaign.getId(), agentId, sessionTypeSession.getId());
				if (openSession == null) {
					// SE CREA NUEVA SESSION
					openSession = new Session();
					openSession.setAgent(agent);
					openSession.setCampaign(campaign);
					openSession.setHost(host);
					//openSession.setPeer(peer);
					openSession.setSessionType(sessionTypeSession);
					openSession.setStartedAt(new Date());
					openSession = sessionEao.createSession(openSession);
					sessionsDto.add(conv.fromSession(openSession));
					// SE CREA NUEVO ESTADO
					Session openState = new Session();
					openState.setAgent(agent);
					openState.setCampaign(campaign);
					openState.setHost(host);
					//openState.setPeer(peer);
					openState.setSession(openSession);
					if (agent.getAutoready()) {
						openState.setSessionType(sessionTypeReady);
					} else {
						openState.setSessionType(sessionTypePause);
					}
					openState.setStartedAt(new Date());
					openState = sessionEao.createSession(openState);
					sessionsDto.add(conv.fromSession(openState));

				} else {
					// SE VERIFICAN ESTADOS ABIERTOS
					Session openState = sessionEao.findOpenStates(openSession
							.getId());
					if (openState == null) {
						// SE CREA NUEVO ESTADO
						openState = new Session();
						openState.setAgent(agent);
						openState.setCampaign(campaign);
						openState.setHost(host);
						//openState.setPeer(peer);
						openState.setSession(openSession);
						if (agent.getAutoready()) {
							openState.setSessionType(sessionTypeReady);
						} else {
							openState.setSessionType(sessionTypePause);
						}
						openState.setStartedAt(new Date());
						openState = sessionEao.createSession(openState);
					}
					sessionsDto.add(conv.fromSession(openSession));
					sessionsDto.add(conv.fromSession(openState));
				}

				// VERIFICA COLAS

				List<String> queues = queueEao.findQueues(campaign.getId());
				String respuesta = managerBean.addManyQueues(queues, peer
						.getName(), peer.getServer().getIp(), peer.getServer()
						.getAmiUser(), peer.getServer().getAmiPassword(), peer
						.getServer().getAmiPort());
				if (respuesta.equals("OK")) {
					if (!agent.getAutoready()) {
						respuesta = managerBean.pauseManyQueues(queues, peer
								.getName(), peer.getServer().getIp(), peer
								.getServer().getAmiUser(), peer.getServer()
								.getAmiPassword(), peer.getServer()
								.getAmiPort());
						if (!respuesta.equals("OK")) {
							throw new CustomExcepcion(
									"La respuesta del Manager es diferente de OK.");
						}
					}
				} else {
					throw new CustomExcepcion(
							"La respuesta del Manager es diferente de OK.");
				}

			}

			return sessionsDto;

		} catch (Exception e) {
			throw new CustomExcepcion(e.getMessage());
		}
	}*/

}
